function fnames_out= osl_render4D(nii,fnameout,workbenchdir,interptype,visualise)
% Creates a surface rendering of a 4D nifti and saves as dense time series
% (.dtseries.nii) CIFTI file
%
% interptype can be 'trilinear' or 'none';
% visualise can be 0 or 1;
% fnames_out is a structure:
%    fnames_out.left:  left hemisphere file name
%    fnames_out.right: right hemisphere file name
%
% Use workbenchview to load multiple files.

% AB 2013
% HL 270513

global OSLDIR;

fnameout = strrep(fnameout,'.gz','');
fnameout = strrep(fnameout,'.nii','');

if ~isempty(strfind(nii,'.nii.gz'))
  ext = '.nii.gz';
elseif ~isempty(strfind(nii,'.nii.gz'))
  ext = '.nii';
else
  error('should be nii or nii.gz file');
end

if ~exist('workbenchdir','var')
  workbenchdir = '/home/hluckhoo/other/workbench/bin_linux64';
end
if ~exist('interptype','var')
  interptype = 'interp';
end
if ~exist('visualise','var')
  visualise = 0;
end

switch lower(interptype)
    case {'interp','trilinear'}
        interptype_vol  = 'trilinear';
        interptype_surf = 'trilinear'; 
    case {'nearestneighbour','nn','none'}
        interptype_vol  = 'nearestneighbour';
        interptype_surf = 'enclosing'; 
    otherwise
end

if ~isdir(fileparts(fnameout)); mkdir(fileparts(fnameout)); end

% Load surfaces to map to
surf_right       = [OSLDIR '/std_masks/ParcellationPilot.R.midthickness.32k_fs_LR.surf.gii'];
surf_left        = [OSLDIR '/std_masks/ParcellationPilot.L.midthickness.32k_fs_LR.surf.gii'];
surf_right_infl  = [OSLDIR '/std_masks/ParcellationPilot.R.inflated.32k_fs_LR.surf.gii'];
surf_left_infl   = [OSLDIR '/std_masks/ParcellationPilot.L.inflated.32k_fs_LR.surf.gii'];
surf_right_vinfl = [OSLDIR '/std_masks/ParcellationPilot.R.very_inflated.32k_fs_LR.surf.gii'];
surf_left_vinfl  = [OSLDIR '/std_masks/ParcellationPilot.L.very_inflated.32k_fs_LR.surf.gii'];

% Resample to 2mm:
osl_resample_nii(nii, fnameout, 2, interptype_vol ,[OSLDIR '/std_masks/MNI152_T1_2mm_brain.nii.gz']);

output_right    = [fnameout '_right.nii'];
output_left     = [fnameout '_left.nii'];

% Map volume to surface
dos([workbenchdir '/wb_command -volume-to-surface-mapping ' fnameout ext ' ' surf_right       ' ' output_right    ' -' interptype_surf]);
dos([workbenchdir '/wb_command -volume-to-surface-mapping ' fnameout ext ' ' surf_left        ' ' output_left     ' -' interptype_surf]);

% Save as dtseries 
cifti_right = strrep(output_right,'.nii','.dtseries.nii');
cifti_left  = strrep(output_left, '.nii','.dtseries.nii');

dos([workbenchdir '/wb_command -cifti-create-dense-timeseries ' cifti_right     ' -right-metric ' output_right]);
dos([workbenchdir '/wb_command -cifti-create-dense-timeseries ' cifti_left      ' -left-metric '  output_left ]);

fnames_out = [];
fnames_out.left = cifti_left;
fnames_out.right = cifti_right;

% View in workbench
if visualise
    workbenchview(fnames_out,workbenchdir);
end
end
